import React, { useState } from 'react'
import { getListApi } from '../api/user'
import Item from '../componts/Item'
import { NavBar, InfiniteScroll } from 'antd-mobile'
import { LoopOutline } from 'antd-mobile-icons'
import { useLoaderData, useSearchParams } from 'react-router-dom'
function List() {
  let loaderData = useLoaderData()
  let [list, setList] = useState(loaderData.list)


  let [sp] = useSearchParams()
  let [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  // 上拉加载
  async function loadMore() {
    setPage((k) => k + 1)
    let obj = { ...Object.fromEntries(sp), page: page + 1 }
    let { data: res } = await getListApi(obj)
    setList([...list, ...res])
    if (res.length === 0) {
      setHasMore(false)
    }
  }

  return (
    <div>
      <NavBar><span>上海</span><LoopOutline /><span>北京</span></NavBar>
      {
        list.map((item) => {
          return <Item key={item.id} {...item} />
        })
      }
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  )
}

export default List

export const loader = async ({ request }) => {
  let url = new URL(request.url)
  let sp = { ...Object.fromEntries(url.searchParams) }
  let { data: res } = await getListApi(sp)
  console.log(res);
  return { list: res }
}